package com.amado.course42Socket.tcp.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by Administrator on 2018/8/7.
 */
public class HelloDialogueService {
	private int port = 9999;
	private ServerSocket serverSocket;

	public HelloDialogueService() throws Exception {
		serverSocket = new ServerSocket(port);
		System.out.println("服务器启动!");
	}

	public void service() {
		try {
			Socket socket = serverSocket.accept();
			System.out.println(socket.getInetAddress() + "  " + socket.getPort());
			PrintWriter printwriter = new PrintWriter(socket.getOutputStream(), true);
			printwriter.print("你已经连接到服务器");
			Scanner scanner = new Scanner(System.in);
			//开启一个线程去读取对方的聊天的信息
			new Thread(new Runnable() {
				@Override
				public void run() {
					BufferedReader bufferedReader = null;
					try {
						bufferedReader = new BufferedReader(
								new InputStreamReader(socket.getInputStream()));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					while (true) {
						try {
							System.out.println(bufferedReader.readLine());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}).start();
			while (true) {
				//主线程负责我的聊天信息输入
				printwriter.println(scanner.nextLine());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		HelloDialogueService server = new HelloDialogueService();
		server.service();
	}
}
